package com.briup.estore.common.service.impl;

import com.briup.estore.common.bean.Admin;
import com.briup.estore.common.dao.IAdminDao;
import com.briup.estore.common.exception.ShopCommonException;
import com.briup.estore.common.service.IAdminService;
import com.briup.estore.common.util.JwtUtil;
import com.briup.estore.common.util.PasswordEncoder;
import com.briup.estore.common.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author adam
 * @date 2022/8/15
 */
@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private IAdminDao dao;

    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    RedisCache redisCache;

    @Override
    public void register(Admin admin)   {
        Admin byUsername = dao.findByUsername(admin.getUsername());
        if (Objects.isNull(byUsername)) {
            admin.setPassword(passwordEncoder.encode(admin.getPassword()));
            dao.save(admin);
        } else {
            throw new ShopCommonException(50001,"用户名已经被占用请重试");
        }
    }

    @Override
    public Map<String, String> login(String username, String password) {
        Admin admin = dao.findByUsername(username);
        if (Objects.isNull(admin)) {
            throw new ShopCommonException(51000,"用户不存在");
        } else {
            if (!admin.getPassword().equals(passwordEncoder.encode(password))) {
             throw new ShopCommonException(51000,"用户名密码错误");
            }else {
                if (!admin.isStats()){
                    throw new ShopCommonException(51000,"账号状态异常");
                }
            }
        }
        String jwt = JwtUtil.createJWT(username);
        //设置30分钟超时
        redisCache.setCacheObject(username, jwt,  JwtUtil.JWT_TTL, TimeUnit.MILLISECONDS);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        map.put("username", username);
        return map;
    }

    @Override
    public void loginOut(String username) {
        redisCache.deleteObject(username);
    }


}
